//
//  API_Actor_Demo1VC.swift
//  APSwift
//
//  Created by jianbo.pei on 2024/8/20.
//

import UIKit

class API_Actor_Demo1VC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
//        test1()
        
//        test2()
        
//        test3()
        
        test4()
    }
    

}
extension API_Actor_Demo1VC {
    actor DownloadManager {
        private var downloads: [URL: Data] = [:]
        
        func startDownload(from url: URL) async -> Data? {
            if let data = downloads[url] {
                return data
            }
            
            do {
                let (data, _) = try await URLSession.shared.data(from: url)
                downloads[url] = data
                return data
            } catch {
                debugPrint("test4 Download failed for URL: \(url), Error: \(error)")
                return nil
            }
        }
        
        func getDownloadedData(for url: URL) async -> Data? {
            return downloads[url]
        }
    }

    // 使用 DownloadManager Actor 的示例
    func runDownloadTasks() async {
        let downloadManager = DownloadManager()
        let urls = [
            URL(string: "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/eca8355fbfd04915ada366fe6fc11e27~tplv-k3u1fbpfcp-jj:480:400:0:0:q75.avis#?w=2600&h=1200&s=240102&e=jpg&b=fffcf3")!,
            URL(string: "https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5b59731a2b7a442890d1b413e569454c~tplv-k3u1fbpfcp-jj:480:400:0:0:q75.avis#?w=1300&h=600&s=684289&e=png&b=d7e1f1")!,
            URL(string: "https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ba2903af64a84ba79d6d6db48665b701~tplv-k3u1fbpfcp-jj:480:400:0:0:q75.avis#?w=780&h=360&s=52813&e=jpg&b=f3f2f2")!
        ]
        
        await withTaskGroup(of: Void.self) { taskGroup in
            for url in urls {
                taskGroup.addTask {
                    if let data = await downloadManager.startDownload(from: url) {
                        debugPrint("test4 Downloaded \(data.count) bytes from \(url)")
                    }
                }
            }
        }
    }
    
    private func test4() {
        /// 运行下载任务示例
        Task {
            await runDownloadTasks()
        }
    }
}

extension API_Actor_Demo1VC {
    actor BankAccount {
        private var balance: Double = 0
        
        /// 存
        func deposit(amount: Double) {
            balance += amount
        }
        
        /// 取
        func withdraw(amount: Double) -> Bool {
            if balance >= amount {
                balance -= amount
                return true
            } else {
                return false
            }
        }
        
        func getBalance() -> Double {
            return balance
        }
    }

    private func test3() {
        let account = BankAccount()

        Task {
            await account.deposit(amount: 100.0)
            let success = await account.withdraw(amount: 50.0)
            let balance = await account.getBalance()
            debugPrint("test3 Withdraw success: \(success), Balance: \(balance)")
        }
    }
    
}

extension API_Actor_Demo1VC {
    actor Counter {
        private var value: Int = 0
        
        func increment() {
            value += 1
        }
        
        func getValue() -> Int {
            return value
        }
    }
    
    /// 使用 Actor 的示例
    func runCounter() async {
        let counter = Counter()
        
        // 并发地执行多次增量操作
        await withTaskGroup(of: Void.self) { taskGroup in
            for _ in 0..<1000 {
                taskGroup.addTask {
                    await counter.increment()
                }
            }
        }
        
        // 获取最终的计数值
        let finalValue = await counter.getValue()
        print("Final Counter Value: \(finalValue)")
    }
    
    private func test1() {
        // 运行示例
        Task {
            await runCounter()
        }
    }
    
    private func test2() {
        let counter2 = Counter()
        Task {
            for _ in 0..<1000 {
                await counter2.increment()
            }
            let result = await counter2.getValue()
            debugPrint("test2 - result is \(result)")
        }
    }
}




